# -*- coding:utf-8 -*-
import json

from flask import Blueprint, request
import pymysql

from apps import result
from apps.views import api_decorator

bp = Blueprint('index', __name__, url_prefix='/index')


@bp.route('/foreign', methods=['POST'])
@api_decorator
def foreign():
    conn = pymysql.connect(host="localhost", user="root", password="123456", db="little_pig", port=3306,
                           charset='utf8')
    client = conn.cursor(cursor=pymysql.cursors.DictCursor)

    sql = 'select * from foreign_news limit 20'
    client.execute(sql)
    data = client.fetchall()
    data = json.dumps(data).replace('<span>', '').replace('</span>', '').replace('<strong>', '[').replace('</strong>',
                                                                                                          ']').replace(
        '&hellip;', '...')
    data = json.loads(data)
    return result.from_data(data)


@bp.route('/chinese', methods=['POST'])
@api_decorator
def chinese():
    content = request.json or {}
    page = content.get('page', 1)
    page = int(page)

    conn = pymysql.connect(host="localhost", user="root", password="123456", db="little_pig", port=3306,
                           charset='utf8')
    client = conn.cursor(cursor=pymysql.cursors.DictCursor)

    sql = 'select * from chinese_news limit {}, {}'.format(20 * (page -1), 20 * page)
    client.execute(sql)
    data = client.fetchall()
    return result.from_data(data)
